package com.jh.netty.server;

import com.jh.netty.instruction.CommunicationPacket;
import com.jh.netty.instruction.DataPacketCMD;
import com.jh.netty.instruction.Instruction;
import com.jh.netty.instruction.datapacket.CmdGetDotStatus;
import com.jh.netty.instruction.datapacket.ControllerHistoryResponseData;
import com.jh.netty.instruction.datapacket.DoorParam;
import com.jh.netty.util.ConvertCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ByteArrayHandler extends SimpleChannelInboundHandler<byte[]> {

    // onmsg
    // 有信号进来时
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
        System.out.println("\n==========处理字节数组==============================");
        System.out.println("byte[] tcpsocket 消息 = " + Arrays.toString(msg));

//        ByteBuf buf=(ByteBuf) msg;
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
////        String body=new String(req, StandardCharsets.UTF_8);
//        System.out.println("服务器端接收的消息：" + Arrays.toString(req));
////
//        List<String> insList = new ArrayList<>();
//        for (byte b : msg) {
//            // 转成16进制
//            String a = String.format("%02x", b);
//            insList.add(a);
//        }
//        // 拼成16进制指令
//        String ins = String.join("", insList);
//        System.out.println("指令 = " + ins);

//        if (ins.startsWith(CommunicationPacket.DEFAULT_BOOT_CODE)) {
//            // 通讯包
//            CommunicationPacket cp = CommunicationPacket.parse(ins);
//            if (cp.isValidCRC16()) {
//                switch (cp.getDataPacket().getCmd()) {
//                    case CMD_OK:
//                        System.out.println("接收正常");
//                        break;
//                    case CMD_Request_Resend:
//                        System.out.println("请求重发");
//                        break;
//                    case CMD_INVALID_CMD_CODE:
//                        System.out.println("无效命令码");
//                        break;
//                    case CMD_INVALID_DATA:
//                        System.out.println("无效数据");
//                        break;
//                    case CMD_DATA_ALL_UPLOAD:
//                        System.out.println("数据已全部上载");
//                        break;
//                    case CMD_GET_DCUID:
//                        System.out.println("取控制器识别码 / 取控制器名称和版本号");
//                        break;
//                    case CMD_GET_DOOR_CONFIG:
//                        List<DoorParam> dp = DoorParam.parse(cp.getDataPacket().getDataCodeText());
//                        System.out.println("取控制器门参数表: " + dp);
//                        break;
//                    case CMD_GET_TIME:
//                        System.out.println("取控制器时间");
//                        break;
//                    case CMD_GET_EVENT:
//                        // 刷卡时的返回值
//                        ControllerHistoryResponseData chrd = ControllerHistoryResponseData.parse(cp.getDataPacket());
//                        System.out.println("取控制器历史事件: " + chrd);
//                        break;
//                    case CMD_GET_DOT_STATUS: // 开关门状态
//                        CmdGetDotStatus cgds = CmdGetDotStatus.parse(cp.getDataPacket());
//                        System.out.println("取控制器所有点状态表: " + cgds);
//                        break;
//                    case CMD_SET_DOOR_CONFIG:
//                        System.out.println("下载控制器门参数表");
//                        break;
//                    case CMD_SET_TIME:
//                        System.out.println("下载系统时间");
//                        break;
//                    case CMD_SET_DOT_STATUS:
//                        System.out.println("下载设置控制器点状态表");
//                        break;
//                }
//
////                // 模拟发送指令
////                ByteBuf bb = Unpooled.buffer();
////                bb.writeBytes(ConvertCode.hexString2Bytes(ins));
////                // ByteBufUtil.
////                // WebSocketFrame wsf = new BinaryWebSocketFrame(bb);
////                // new BinaryWebSocketFrame(Unpooled.copiedBuffer(req))
////                ChannelSupervise.send(bb);
////                CommunicationPacket scp = CommunicationPacket.parse("52 52 01 01 00 01 40 F0 62");
////                ChannelSupervise.send(scp.toByteBuf());
//            } else {
//                // crc 无效时
//                System.out.println("crc16 无效");
//            }
//        } else {
//            Instruction instruction = Instruction.parse(ins);
//
//            ByteBuf bb = Unpooled.buffer();
//            if (instruction.getData() == null) {
//                // 心跳指令，这里回复心跳
//                bb.writeBytes(ConvertCode.hexString2Bytes("04" + instruction.getAddressCode() + instruction.getCmd() + "81" + instruction.getCheckCode()));
//            } else if (instruction.getData().length() == 12) {
//                // 如果data为mac地址，那么为握手指令，在这里回复握手指令
//                bb.writeBytes(ConvertCode.hexString2Bytes("04" + instruction.getAddressCode() + instruction.getCmd() + "81" + instruction.getCheckCode()));
//            } else {
//                // 无效
//                bb.writeBytes(ConvertCode.hexString2Bytes("04" + instruction.getAddressCode() + instruction.getCmd() + DataPacketCMD.CMD_INVALID_CMD_CODE.getCmd() + instruction.getCheckCode()));
//            }
//            ctx.channel().writeAndFlush(bb);
//
////            ChannelSupervise.send(bb);
////            if("0901aa003e0500591500".equalsIgnoreCase(ins)) {
////                System.out.println("握手 回复 = 0401aa8100");
////                ByteBuf bb = Unpooled.buffer();
////                bb.writeBytes(ConvertCode.hexString2Bytes("0401aa8100"));
////                ChannelSupervise.send(bb);
////            } else if("03019800".equalsIgnoreCase(ins)) {
////                System.out.println("心跳 回复 = 0401988100");
////                ByteBuf bb = Unpooled.buffer();
////                bb.writeBytes(ConvertCode.hexString2Bytes("0401988100"));
////                ChannelSupervise.send(bb);
////            }
//        }

//        ChannelSupervise.findChannel(incoming.id().asShortText());
//        for (Channel channel : channels) {
//            System.out.println("ip = " + channel.remoteAddress().toString());
//            if (channel != incoming) { //排除当前通道
//                String str = String.format("[%s]说: %s\n", incoming.remoteAddress().toString().substring(1), s);
//                channel.writeAndFlush(str);
//            }
//        }

//        if(msg instanceof FullHttpRequest) {
//            handHttpRequest(ctx, (FullHttpRequest) msg);
//        } else if(msg instanceof WebSocketFrame) {
//            handWsMessage(ctx, (WebSocketFrame) msg);
//        }
        // 回复消息
//        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器连接成功！"));
        System.out.println("========================================\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("tcp active");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("tcp inactive");
    }

    // onerror
    // 发生异常时
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel incoming = ctx.channel();
        System.out.println("[Server]:" + incoming.remoteAddress().toString().substring(1) + "异常");
        ctx.close();
    }
}
